;
var terminal = 1;
if(!passport.isLogin()){
	$('.think_user .think_login a').eq(1).attr('href','javascript:;');
	$('.think_user .think_login a').eq(1).click(function(){
	        logobj.showlogin(function(){window.location.reload()});
	});
};

var Buy = (function(){
    var _buy = {};
    _buy.limit = cartSingleRowLimit;
    // 联想服务显示隐藏
    _buy.service = function(){
    	$('.buycart').on('click', '.choose_service', function(){
    		//查询已选择的服务
    		$tr = $(this).closest('tr')
    		$next = $tr.next('tr:first');
    		/**已选服务列表**/
    		var selectedlist = [];
    		if($next.hasClass('bc_gift')){
    			$next.find('ul.bc_gift_top').each(function(){
    				var one = {};
    				var gcode = $(this).attr('gcode');
    				var ccode = $(this).attr('ccode');
    				one.gcode = gcode;
    				one.ccode = ccode;
    				selectedlist.push(one);
    			});
    		}
    		/*选中已选择的服务列表*/
    		$tr.find('select').each(function(){
    			//重置
    			$(this).find('option:first').attr("selected",true);
//    			var gcode = $(this).attr('gcode');
    			for(var i=0; i < selectedlist.length; i++){
    				var tmp = selectedlist[i];
    				var $option = $(this).find('option[gcode=' + tmp.gcode+']');
    				if($option.length){
    					$option.attr("selected",true);
    				}
    			}
    		});
    		
    		$(this).siblings('.service_box').show();    		
    	});
    	
    	$('.buycart').on('click', '.service_cancel', function(){
    		 $(this).parents('.service_box').hide();   		
    	});
    	//选择服务
    	$('.buycart').on('change', 'select', function(){
    		var selectlist = [];
    		var self = $(this);
    		self.closest('ul').find('select').each(function(){
    			var option = $(this).find('option:selected');
    			if(!option.attr('gcode')){
    				return;
    			}
    			var data = {};
    			var ccode = $(this).attr('ccode');
    			data.ccode = ccode;
    			data.gcode = option.val();
    			data.gname = option.text();
    			selectlist.push(data);
    		});
    	});
    	
    	
    	//选择服务确定
    	$('.buycart').on('click', '.service_ok', function(){
    		var scodes = [];
    		var $tr = $(this).closest('tr');
    		var list = [];
    		$tr.find('select').each(function(){
    			var option = $(this).find('option:selected');
    			var ccode = $(this).attr('ccode');
    			if(option.attr('value')){
    				var serv = {};
    				serv.ccode = ccode;
    				serv.gcode = option.attr('gcode');
    				serv.gname = option.attr('gname');
    				serv.gprice = option.attr('gprice');
    				serv.num = $tr.find('input.pro_num').val();
    				serv.xiaoji = parseFloat(serv.gprice) * parseFloat(serv.num).toFixed(2);
    				list.push(serv);
    				scodes.push(serv.gcode);
    			}
    		});
    		
    		$sibling = $tr.next('tr:first');
    		
    		//请求修改服务
    		var gcode = $tr.attr('gcode');
    		
    		//调用接口增加
            var urlmodifyitem = 'updateitemservice.jhtm';
            var data = {   
            		terminal: terminal, 
            		itemId: gcode, 
            		services: scodes.join(','), 
            		ss: new Date().getTime() 
        			};
            $.get(urlmodifyitem, 
            		data, 
            		function (data) {
                    if(typeof (data) == "string"){
                        data = JSON.parse(data);
                    }
                	if (data.rc == "0") {
                		refreshCart(data.html);
                	}
                	else{
                		showMessage(3000, data.msg);
                	}
            });
    	});
    	
    };


    //form值加减
    _buy.num = function(){
    	
    	$('.buycart').on('click', '.i_box .J_add', function(){
    		var $tr=$(this).closest('tr');
        	if($tr.hasClass('disable')){
        		return;
        	}
        	
            var oldValue = parseInt($(this).siblings(".J_input").val());
            var newValue = oldValue + 1;
            var stock = parseInt($tr.attr('stock'));
            if(newValue > stock){
            	 showMessage(3000,"库存不足");
            	return ;
            }
            
            try{
                if(newValue > _buy.limit) {
                	 showMessage(3000,"该商品您最多只能购买" + _buy.limit + "件");
                	return;
                }
            }catch(e){
            }
            $(this).siblings(".J_input").val(newValue);
			
            updaterownum($tr, oldValue, newValue);
            return false;
    	});
    	
    	$('.buycart').on('click', '.i_box .J_minus', function(){
    		var $tr=$(this).closest('tr');
         	if($tr.hasClass('disable')){
         		return;
         	}
         	
            var oldValue=parseInt($(this).siblings(".J_input").val());
            var newValue = oldValue - 1;
            if(newValue < 1){
                 $(this).siblings(".J_input").val(1);
                 return;
            }else{
                 $(this).siblings(".J_input").val(newValue);
            } 
            updaterownum($tr, oldValue, newValue);
            return false;     
    	});
    	
    	$('.buycart').on('blur', '.i_box .J_input', function(){
    		  var $tr=$(this).closest('tr');
              if($tr.hasClass('disable')){
                  return;
              }

              var oldValue = parseInt($(this).attr('val'));
              var newValue = parseInt($(this).val());
              var stock = parseInt($tr.attr('stock'));
              if(newValue > stock){
              	 showMessage(3000,"库存不足");
              	$(this).val(oldValue);
              	return ;
              }

              
              try{
                  if(newValue > _buy.limit) {
                      newValue = _buy.limit;
                  }
                  if(newValue <= 0){
                      newValue = 1;
                  }
              }catch(e){
              }

              $(this).val(newValue);

              updaterownum($tr, oldValue, newValue);
              return false;
    	});

        $(document).delegate('.J_input', 'keypress', function (event) {
			var $tr=$(this).closest('tr');
			if($tr.hasClass('disable')){
        		return false;
        	}
			
			var keyCode = event.which;
			if (keyCode == 46 || (keyCode >= 48 && keyCode <= 57))
				return true;
			else
				return false;
		});
		//$(document).delegate('.J_input', 'focus', function () {
		//	this.style.imeMode = 'disabled';
		//});

       
    };
    
    _buy.bindChooseAll = function(){
    	$('.buycart').on('click', '.bc_all', function(){
			var itemid = [];
			$('#main_table tr').each(function(){
                var rowid = $(this).attr('gcode');
                if(rowid){
                    itemid.push(rowid);
                }
			});
			if(itemid.length == 0){
				return;
			}
    		var div = $(this).closest('div');
    		if(div.hasClass('active')){
    			$(".bc_all").closest('div').removeClass('active');
				$('#main_table tr').removeClass('active');
				activeItem(itemid.join('@'), false);
    		}else{
    			$(".bc_all").closest('div').addClass('active');
    			$('#main_table tr').addClass('active');
				activeItem(itemid.join('@'), true);
    		}
    	});
    }
    
    
    _buy.getServices = function(){
		$("#main_table tr").not('.disable').not('.bc_gift').each(function(index){
			//console.log(index);
			if(index == 0){
				return;
			}
			var self = $(this);
			var type = self.attr('type');
			var mainGcode = self.attr('gcode');
			if(type == 2 || type == 3){
				mainGcode = mainGcode.split(',')[0];
			}
			
			var html = "";
			var urlservice = 'getservicelist.jhtm';
			var sprow = $(this);
			$.ajax({
				type: "get",
				url: urlservice,
				data: { terminal: terminal, gcode: mainGcode, ss: new Date().getTime() },
				async: false,
				success: function (data) {
                data = JSON.parse(data);
                if(data != null){
                    if (data.rc == "0") {
                        var count = 0;
                        if (data.servicelist != null && data.servicelist.length > 0) {
                            var text = template('serviceSelect', {list:data.servicelist});
                            self.find('.bc_service').html(text);

                        }
                    }
                }
            }
        });
		
		});
    }
    
    _buy.bindChoose = function(){
    	$('.buycart').on('click', '.bc_table_sel a', function(){
    		var tr = $(this).closest('tr');
			var gcode = tr.attr('gcode');
			
    		if(tr.hasClass('active')){
    			tr.removeClass('active');
				activeItem(gcode, false);
    		}else{
    			tr.addClass('active');
				activeItem(gcode, true);
    		}
    		updateSelectAll();
    	});
    }

    
    _buy.bindRowDel = function(){
    	$('.buycart').on('click', '.bc_num_del', function(){
    		var tr = $(this).closest('tr');
			var gcodes = [];
			$('tr.active').each(function(){
				var gcode = $(this).attr('gcode');
				gcodes.push(gcode);
			});
			if(gcodes.length == 0){
				 showMessage(3000,'没有选中商品');
				return false;
			}
			opencover("删除操作", "确认删除吗？", "deletegode('" + gcodes.join('@') + "')");
    	});
    }

    	var updateSelectAll = function(){
    		//判断如果全选可勾选全选，否则去掉全选
    		//去掉全选勾
    		var ischooseall = true;
    		$('#main_table tr:gt(0)').not('.pink_table').not('.bc_gift').each(function(){
    			if(!$(this).hasClass('active')){
    				ischooseall = false;
    				return false;
    			}
    		});
    		if(ischooseall){
    			$(".bc_all").addClass('active');
    		}else{
    			$(".bc_all").removeClass('active');
    		}

		}
    	
    _buy.updateSelectAll = updateSelectAll;
    
    _buy.bindSubmitOrder = function(){
    	$('.buycart').on('click', '#submit', function(){    	
    		if(!passport.isLogin()){
    			passport.login = submitcallback;
    			passport.show();
    			return;
    		}
			submitGoods_track();//易分析数据采集--提交选中商品
    		submitcallback();
    	});
    	
    }
	//*提交选中商品-易分析*//
	window._trackData = window._trackData || [];//必须为全局变量，假如之前并没有声明，请加此行代码；
	function submitGoods_track(){
		var gcodes_in_cart = [];
		$("#main_table tr.active").each(function(){
			var code = $(this).attr('gcode');
			if(code){
				gcodes_in_cart.push(code);
			}
		});
		var maingcodes = gcodes_in_cart.join('|');
		_trackData.push(['show','goodsincart', 'latag_pc_shopcart_pay_' + maingcodes])
	}

    var submitcallback = function(){
		var ids = [];
		var existNoStock = false;
		$('#main_table tr.active').each(function(){
			if($(this).hasClass('disable')){
				existNoStock = true;
				return false;
			}
			if($(this).attr('gcode')){
				ids.push($(this).attr('gcode'));
			}
		});
		if(existNoStock){
			showMessage(3000,'部分选中的商品无库存');
			return false;
		}
		if(ids.length == 0){
			showMessage(3000,'没有选中商品');
			return false;
		}
		window.location.href = 'checkout.jhtm?terminal=' + terminal;
    }

    //虚拟表单，post提交
    function post(URL, PARAMS) {
        var temp = document.createElement("form");
        temp.action = URL;
        temp.method = "post";
        temp.style.display = "none";
        for (var x in PARAMS) {
            var opt = document.createElement("textarea");
            opt.name = x;
            opt.value = PARAMS[x];
//             showMessage(3000,opt.name);
//             showMessage(3000,opt.value)
            temp.appendChild(opt);
        }
        document.body.appendChild(temp);
        // showMessage(3000,temp);
        temp.submit();
        return temp;
    }



    //清空购物车
    _buy.bindEmptyCart = function () {
		$("#clearmycart").click(function(){
			opencover("清空操作", "确定要清空购物车吗？", "emptycart()");
		});
    }
    
//    _buy.updateXiaoji = function(){
//    	$("#main_table tr").not('.bc_gift').each(function(){
//    		var num    =   $(this).find('input.pro_num').val();
//    		updateXiaoJi2($(this), num);
//    	});
//    }
  
	
    var updaterownum = function($tr, num, newVal){
    	var gcode = $tr.attr('gcode');
    	var url = 'modifycaritemcount.jhtm';
    	$.get(url, {terminal:terminal, icount: newVal, itemId: gcode }, function (data) {
            if(typeof (data) == "string"){
                data = JSON.parse(data);
            }
    		if (data.rc == 0) {
    			refreshCart(data.html);
    		}else if(data.rc == 2){
    			$tr.find('.J_input').val(num);
                 showMessage(3000,"库存数量不足，商品数量不可增加！");
            } else {
            	$tr.find('.J_input').val(num);
    			 showMessage(3000,"修改购物车失败!");
    		}
    	});
    }
	
	var activeItem = function(itemid, active){
		var url = 'activeItem.jhtm';
		$.get(url, {terminal:terminal, itemId: itemid, active: active }, function (data) {
            if(typeof(data) == "string"){
                data = JSON.parse(data);
            }
    		if (data.rc == 0) {
    			$('#cart_main').html(data.html);
    			refreshCart(data.html);
    		} else {
				//showMessage(1000, "同步购物车失败!");
				 showMessage(3000,"修改购物车失败!");
			}
    	});	
	}


    _buy.bindShowFullReduction = function(){
    	$('.buycart').on('click', '.table_cx',function(){
    		$(this).next('.table_cx_main').show();
    	});
    	
    	$('.buycart').on('click', '.table_cx_mainqr',function(){
    		var gcode = $(this).closest('tr').attr('gcode');
            var promotionid = "-1";
            $(this).closest('.table_cx_main').find('input:radio').each(function(){
            	if($(this).attr('checked') == 'checked'){
            		promotionid = $(this).attr('promotionid'); 
            	}
            });
            
            var data = {terminal:terminal,
            		gcode: gcode, 
            		promotionid: promotionid};
        	
            $.ajax({
	            url: "usepromotion.jhtm",
	            data: data,
	            success:function(data) {
                    if(typeof (data) == "string"){
                        data = JSON.parse(data);
                    }
	            	if (data.rc == 0) {
	            		refreshCart(data.html);
	            	}else{
	            		 showMessage(3000,"修改购物车失败!");
	            	}
	            }
            });
        });
    	
    	$('.buycart').on('click', '.table_cx_mainqx', function(){
    		$(this).closest('.table_cx_main').hide();
    	});

    }
	

    
    return _buy;

})(jQuery, Buy)


$(function(){
    // select
    $(".selectContainer").select();

    /* 产品图轮播*/
    $("#lunbo-img").lantern({     
        "goNO"     : 4,           //定义轮播个数（默认1），1-5可选 小于一屛格子数
        "boxNO"    : 4,           //定义一屛格子数量（默认5），如果滚动数量大于这个数量，将被设置成该数量
        "left_bt"  : "#rgt-btn",  //定义左侧按钮
        "right_bt" : "#lft-btn",  //定义右侧按钮
        "speed"    : 700         //定义滚屏速度（默认500，越大越慢）
    });

    Buy.getServices();
    
//    Buy.updateXiaoji();
    // 联想服务显示隐藏
    Buy.service();

    //form值加减
    Buy.num();
    //全部选择
    Buy.bindChooseAll();
    //删除绑定
    Buy.bindRowDel();
    
    Buy.bindSubmitOrder();
    
    Buy.bindChoose();
    
    Buy.bindEmptyCart();
    
    Buy.updateSelectAll();

    Buy.bindShowFullReduction();

	//推荐商品
	var gcodes =[];
	$("#main_table tr.active").each(function(){
		gcodes.push($(this).attr('gcode'));
	});
	//console.log(JSON.stringify(gcodes));
	
	function getrecommends(){
		$.ajax({
			url: "" +product_index+ '/api/products/getrecommends'+"",
			dataType:'jsonp',
			data:{salesPlat:terminal, goodsCodes: gcodes.join(','), nums: 8 },
			jsonp:'callback',
			success:function(data) {
				if(data.length == 0){
					$("#bc_prolist").hide();
					return;
				}
				var text = template('recommend',{list: data, gcodes:gcodes.join("|")});
				$("#bc_prolist").html(text);
				$("#lunbo-img").lantern({
					"goNO"     : 4,           //定义轮播个数（默认1），1-5可选 小于一屛格子数
					"boxNO"    : 4,           //定义一屛格子数量（默认5），如果滚动数量大于这个数量，将被设置成该数量
					"left_bt"  : "#rgt-btn",  //定义左侧按钮
					"right_bt" : "#lft-btn",  //定义右侧按钮
					"speed"    : 700         //定义滚屏速度（默认500，越大越慢）
				});
				//监控，无法保证执行顺序，写到业务代码里了
				recommend_track();
				
			}
		});
	}

	if(shopId != 3){
		getrecommends();
	}

    $('img').error(function(){
        $(this).attr('src', pcCssHomeModule+'/images/pic_lost.jpg');
    });
    
})



//删除一行
function deleline(_this) {
	opencover("删除操作", "确认删除吗？", "deletegode('" + _this + "')");
}
function deletegode(str) {
	var totalmoneyf = $("#totalmoneyf").text();
/*	if ( totalmoneyf == '0' ||  totalmoneyf == '0.0' || totalmoneyf == '0.00') {
		$("#submit").css("background", "#e00000");
	}
*/	var url = 'deleteitemfromcart.jhtm';
	gcode= [];
	gcode.push(str);
	$.get(url, { terminal: terminal, itemIds: gcode.join('@') }, function (data) {
		if(typeof(data)=='string'){
			data = JSON.parse(data);
		}
		if (data.rc == 0) {
			closecover();
			refreshCart(data.html);
		} else {
			showMessage(3000, "同步购物车失败！");
			updatebtnsubmitbtn();
		}
	});
}

function refreshCart(html){
	$('#cart_main').html(html);
	//刷新服务
	Buy.getServices();
	Buy.updateSelectAll();
}


function deleservice(_this) {
	var totalmoneyf = $("#totalmoneyf").text();
	if ( totalmoneyf == '0' ||  totalmoneyf == '0.0' || totalmoneyf == '0.00') {
		$("#submit").css("background", "#e00000");
	}
	var url = 'deleteservice.jhtm';
	//获取要删除的服务code
	var servicecode = $(_this).closest('ul').attr('gcode');
	var gcode = $(_this).closest('tr').prev().attr('gcode');
	$.get(url, { terminal:terminal, itemId: gcode, service:servicecode }, function (data) {
		if(typeof(data)=='string'){
			data = JSON.parse(data);
		}
		if (data.rc == 0) {
			closecover();
			refreshCart(data.html);
		} else {
			showMessage(3000, "同步购物车失败！");
			updatebtnsubmitbtn();
		}
	});
}

//*删除选中商品-易分析*//
	window._trackData = window._trackData || [];//必须为全局变量，假如之前并没有声明，请加此行代码；
function delGoods_track(){
	var gcodes_in_cart = [];
	$("#main_table tr.active").each(function(){
		var code = $(this).attr('gcode');
		if(code){
			gcodes_in_cart.push(code);
		}
	});
	var maingcodes = gcodes_in_cart.join('|');
	_trackData.push(['show','goodsincart', 'latag_pc_shopcart_delcar_' + maingcodes])
}

//删除购物车选中商品
function deletegodeall (){
	var itemids = [];
	$('#main_table tr.active').each(function(){
		itemids.push($(this).attr('rowid'));
	});
	if(itemids.length == 0){
		 showMessage(3000,'没有选中商品');
		return false;
	}
	delGoods_track();//易分析删除数据采集
	var url = 'deleteitemfromcart.jhtm';
	$.get(url, {terminal:terminal, itemid: itemids.join(',') }, function (data) {
		data = JSON.parse(data);
		if (data.rc == 0) {
			window.location.reload();
		} else {
			 showMessage(3000,data.msg);
		}
	});
}

var emptycart = function(){
    var url = 'deleteallitemfromcart.jhtm';
    $.get(url, { }, function (data) {
        data = JSON.parse(data);
        if (data.rc = "0") {
            ///重新获取购物车rejosn
            window.location.reload();
        }
        else {
            showMessage(3000, data.msg);
        }
    });
}


//推荐商品加入购物车
$('#bc_prolist').on('click', '.bc_btn', function(){

	var gcodes =($(this).attr('gcode'));
	var url = 'additemtocart.jhtm';
	var itemtype = 0;
	var icounts = 1;

	var timestamp = Date.parse(new Date());  //时间戳，用来加入车后刷新页面

	$.get(url, {itemtype:itemtype, icount:icounts, gcodes:gcodes}, function (data) {
		if (data.rc == 0) {
			   window.location.href =  '/getcart.jhtm?_=' + timestamp;

		} else {
			 showMessage(3000,data.msg);
		}
	});

});

//更新按钮状态
function updatebtnsubmitbtn(){
    if ($("#totalmoneyf").text() != 0.00) {
        $("#btn_submit").attr("disabled", false).css("background", "#e00000");
    } else {
        $("#btn_submit").attr("disabled", true).css("background", "#c0c0c0");
    }
}

$(function () {
	
	/*无库存不选中*/
	$('#plistsf .sprow').each(function(){
		var self = $(this);
		var stock = self.find('.stores').attr('value');
		if(stock == 0 || stock == "0"){
			self.find('input:checkbox').removeAttr("checked");
		}
	});
	
	$('.product-check').click(function(){
		var self = $(this);
		var stock = self.closest('.sprow').find('.stores').attr('value');
		if(stock == 0 || stock == "0"){
			self.removeAttr("checked");
			 showMessage(3000,'暂无库存');
			return false;
		}
		setTotal();
	});
});


//收藏
function conllectionFun(gcode){
    if(!passport.isLogin()){
        passport.show();
        return;
    }
    var queryGcode = gcode.split(",", 1)[0];
    $.ajax({ //查询是否收藏
        url:queryCollectionUrl,
        type: "GET",
        dataType: "jsonp",
        async:false,
        data: {"gcode":queryGcode},
        jsonp:'callbackparam',
        success: function (data) { // rc:0:已收藏 1:未收藏
            if(data.rc==0){
                showMessage(3000,data.msg);
            }else if(data.rc==1){
                addCollectionFun(gcode);
            }else{
                showMessage(3000,"登录过期，请重新登录！");
            }
        },
        error:function(e){
            console.log("error")
            console.log(e);
        }
    })
}

//添加收藏
function addCollectionFun(gcode) {
    var addGcode = queryGcode = gcode.split(",", 1)[0];
    $.ajax({
        url:addCollectionUrl,
        type: "GET",
        dataType: "jsonp",
        async:false,
        data: {"gcode":addGcode},
        jsonp:'callbackparam',
        success: function (data) { // rc:0:添加收藏成功 1:非独立销售商品不可收藏 -1：收藏失败
            if(data.rc==0){
               showMessage(3000, "收藏成功！");
                deletegode(gcode);
            }else if(data.rc==1){
                showMessage(3000,"非独立销售商品不可收藏！");
            }else if(data.rc==-1){
                showMessage(3000,"收藏失败！");
            }else{
                showMessage(3000,"网络异常！");
            }
        },
        error:function(e){
            showMessage(3000,"收藏异常！");
            console.log("error")
            console.log(e);
        }
    });
}

